﻿//  Copyright (c) 2009 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DNA.Mvc.jQuery;
using DNA.Mvc.Security;
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.RelyingParty;
using Microsoft.Web.Helpers;
using DNA.Mvc.UI;
using DotNetOpenAuth.OAuth;
using System.Configuration;
using System.Web.Configuration;
//using DotNetOpenAuth.OAuth2;
using System.Net;
//using DNA.Mvc.Facebook;
//using DotNetOpenAuth.ApplicationBlock.Facebook;

namespace DNA.Mvc.Controllers
{
    //[HandleError(ExceptionType = typeof(PageNotFoundException), View = "NotFound")]
    //[HandleError(View = "Error")]
    public class AccountController : Controller
    {
        private IFormsAuthentication FormsAuth;
        private IMembershipService MembershipService;
        private WebSiteContext _context;

        public AccountController(WebSiteContext context, IFormsAuthentication formsAuth, IMembershipService membership)
        {
            this._context = context;
            this.FormsAuth = formsAuth;
            this.MembershipService = membership;
        }

        public ActionResult Receive()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Receive(string userName, string email)
        {
            //var _userName = userName;
            var userExists = false;

            if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(email))
            {
                ViewData["Summary"] = Resources.language.Receive_EmailCouldNotBeEmpty;
                return View();
            }

            MembershipUser user = null;
            if (!string.IsNullOrEmpty(userName))
            {
                user = Membership.GetUser(userName);
                if (user != null) userExists = true;
            }


            if (!userExists && !string.IsNullOrEmpty(email))
            {
                var _userName = Membership.GetUserNameByEmail(email);
                if (string.IsNullOrEmpty(_userName))
                {
                    userExists = true;
                    user = Membership.GetUser(_userName, false);
                }
            }

            if (userExists)
            {
                var _event = new ReceivePasswordEvent(user.Email);
                _event.HttpContext = HttpContext;
                _event.Raise();
                return RedirectToAction("PasswordSent", new { email = user.Email });
            }
            else
            {
                ViewData["Summary"] = Resources.language.Receive_UserNotFound;
                return View();
            }
        }

        public ActionResult PasswordSent(string email)
        {
            ViewData.Model = email;
            return View();
        }

        public JsonResult GetSuggests(string term)
        {
            var names = MembershipService.GetSuggestUserNames(term, 10);
            return Json(names, JsonRequestBehavior.AllowGet);
        }

        //[OutputCache(CacheProfile = "UserProfileCache")]
        public ActionResult Info(string userName)
        {
            var username = userName;
            if (string.IsNullOrEmpty(userName))
            {
                if (HttpContext.Request.IsAuthenticated)
                    username = HttpContext.Profile.UserName;
                else
                    return HttpNotFound();
            }

            if (Membership.GetUser(username) != null)
                return View(UserProfile.GetProfile(username));
            else
                return HttpNotFound();
        }

        public ActionResult ValidateEmail(string token)
        {
            if (!string.IsNullOrEmpty(token) && HttpContext.Cache[token] != null && !string.IsNullOrEmpty(HttpContext.Cache[token].ToString()))
            {
                var email = HttpContext.Cache[token].ToString();
                HttpContext.Cache.Remove(token);
                var userName = Membership.GetUserNameByEmail(email);

                if (!string.IsNullOrEmpty(userName))
                {
                    FormsAuth.SignIn(userName, false);
                    var pwdLength = MembershipService.MinPasswordLength;
                    ViewData["PasswordLength"] = pwdLength;
                    var user = Membership.GetUser(userName);
                    var model = new ChangePasswordModel() { };
                    model.OldPassword = user.ResetPassword();
                    return View("ChangePassword", model);
                }
            }
            return RedirectToAction("Login");
        }

        [PersonalOnly]
        [MyControlPanel(ResKey = "RES_PROFILE", Sequence = 1, Group = "Personal", GroupResKey = "RES_PERSONAL_SETTINGS")]
        public ActionResult Profile()
        {
            ViewData.Model = UserProfile.GetProfile(User.Identity.Name);
            return PartialView();
        }

        [PersonalOnly, HttpPost, ValidateInput(false), MyControlPanel]
        public ActionResult Profile(FormCollection form)
        {
            var profile = UserProfile.GetProfile(User.Identity.Name);
            if (TryUpdateModel(profile, "UserProfile"))
            {
                if (!string.IsNullOrEmpty(profile.Language))
                {
                    GE.SetLanguageCookie(HttpContext, "userLanguage", profile.Language);
                    GE.GetCurrentCulture(HttpContext);
                }
                profile.Save();
            }
            new ProfileSavedEvent(profile).Raise(HttpContext);
            return PartialView(profile);
        }

        [Pagable, Authorize]
        public ActionResult UserList(QueryParams _params)
        {
            int total = 0;
            MembershipUserCollection members = null;

            if (!string.IsNullOrEmpty(_params.Filter))
            {
                var filters = _params.GetFilterExpressions();
                var filter = filters[0];
                if (!string.IsNullOrEmpty(filter.Term))
                    members = Membership.FindUsersByName(filter.Term.Replace("'", ""), _params.Index == 0 ? _params.Index : _params.Index - 1, _params.Size, out total);
                else
                    members = Membership.GetAllUsers(_params.Index == 0 ? _params.Index : _params.Index - 1, _params.Size, out total);
            }
            else
                members = Membership.GetAllUsers(_params.Index == 0 ? _params.Index : _params.Index - 1, _params.Size, out total);

            var values = new List<MembershipUser>();
            foreach (MembershipUser member in members)
                values.Add(member);

            return View(new ModelWrapper()
            {
                Model = values,
                Total = total
            });
        }


        [SiteMapAction(Title = "Login",
            IsShared = true,
            ShowInMenu = false)]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login([Bind(Prefix = "LogOnModel")] LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuth.SignIn(model.UserName, model.RememberMe);
                    //new UserLoginEvent(model.UserName, HttpContext).Raise();
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        if (_context.EnablePersonalWeb)
                            return Redirect(_context.ApplicationPath + "/sites/" + model.UserName + "/index.html");
                        return Redirect((!string.IsNullOrEmpty(_context.Web.DefaultUrl) ? _context.Web.DefaultUrl : _context.ApplicationPath));
                    }
                }
                else
                {
                    ModelState.AddModelError("", Resources.language.Logon_UserNotFound);
                }
            }
            return View();
        }

        public ActionResult LogOff()
        {
            FormsAuth.SignOut();
            var web = _context.Web;
            return Redirect(string.IsNullOrEmpty(web.DefaultUrl) ? _context.ApplicationPath : web.DefaultUrl);
            //RedirectToAction("Index", "Home");
        }

        [SiteMapAction(Title = "Register", IgnoreRouteDataKeys = new string[] { "openId" }, IsShared = true, ShowInMenu = false)]
        public ActionResult Register(string openId)
        {
            if (!string.IsNullOrEmpty(openId))
            {
                ModelState.AddModelError("", string.Format(Resources.language.OpenID_AccountNotFound, openId));
            }

            if (_context.Web.EnableUserRegistration)
            {
                ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
                return View();
            }
            else
            {
                return HttpNotFound();
                // throw new HttpException(404, "Page not found.");
            }
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model, string returnUrl = "")
        {
            if (_context.Web.MasterTools.EnableReCaptcha)
            {
                if (!ReCaptcha.Validate(_context.Web.MasterTools.ReCaptchaPrivateKey))
                {
                    ModelState.AddModelError("", Resources.language.reCapticha_KeyUnvalidate);
                    return View(model);
                }
            }

            if (ModelState.IsValid)
            {
                string[] reserves = new string[] { "host", "home", "index", "default", "{blog}", "sites", "{site}" };
                if (reserves.Contains(model.UserName.ToLower()))
                {
                    ModelState.AddModelError("", string.Format(Resources.language.Register_UserNameReserved, "\"" + model.UserName + "\""));
                }
                else
                {
                    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        FormsAuth.SignIn(model.UserName, true);
                        Roles.AddUserToRole(model.UserName, "guests");//default user role

                        var registerEvent = new UserRegistedEvent(model.UserName, model.Password, model.Email);
                        registerEvent.Raise(HttpContext);

                        if (ValueProvider.GetValue("OpenID") != null)
                        {
                            string _openID = ValueProvider.GetValue("OpenID").AttemptedValue;
                            _context.DataContext.OpenIDs.AddOpenID(model.UserName, _openID);
                        }

                        if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }

                        if (_context.EnablePersonalWeb)
                            return Redirect(_context.ApplicationPath + "/sites/" + model.UserName + "/index.html");

                        return Redirect((!string.IsNullOrEmpty(_context.Web.DefaultUrl) ? _context.Web.DefaultUrl : _context.ApplicationPath));
                    }
                    else
                    {
                        ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                    }
                }
            }

            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        [Authorize]
        public ActionResult ChangePassword()
        {

            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            var web = _context.RootWeb;
            var reCaptchaEnabled = web.MasterTools.EnableReCaptcha && (!string.IsNullOrEmpty(web.MasterTools.ReCaptchaPrivateKey)) && (!string.IsNullOrEmpty(web.MasterTools.ReCaptchaPublicKey));

            if (reCaptchaEnabled)
            {
                if (!ReCaptcha.Validate(_context.RootWeb.MasterTools.ReCaptchaPrivateKey))
                    return View(model);
            }

            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    var _event = new PasswordChangedEvent(User.Identity.Name, model.OldPassword, model.NewPassword);
                    _event.Raise(HttpContext);
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", Resources.language.PasswordIncorrect);
                }
            }

            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ActionResult ChangePasswordSuccess()
        {

            return View();
        }

        //protected override void OnActionExecuting(ActionExecutingContext filterContext)
        //{
        //    if (filterContext.HttpContext.User.Identity is WindowsIdentity)
        //    {
        //        throw new InvalidOperationException(Resources.language.WinAuthNotSupported);
        //    }
        //}

        [Authorize(Roles = "administrators")]
        public ActionResult BulkMail()
        {
            return View();
        }

        [Authorize(Roles = "administrators"), HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
        public ActionResult BulkMail(string subject, string body)
        {
            var index = 0;
            var total = 0;
            var members = Membership.GetAllUsers(index, 50, out total);
            int totalPages = (int)Math.Ceiling((double)total / 50);
            int t;

            if (!string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body))
            {
                for (int i = 0; i < totalPages; i++)
                {
                    if (i > 0)
                        members = Membership.GetAllUsers(i - 0, 50, out t);
                    //var emailList = new List<string>();
                    foreach (MembershipUser member in members)
                        DNA.Mvc.WebMail.Send(_context.RootWeb.Title, member.UserName, subject, body);
                    //    emailList.Add(member.UserName);
                    //DNA.Mvc.WebMail.Send(_context.RootWeb.Title, string.Join(",", emailList.ToArray()), subject, body);
                }
            }

            return View();
        }

        [Authorize]
        [HttpGet]
        public ActionResult SendMail(string username)
        {
            ViewData["Receiver"] = username;
            return PartialView();
        }

        [Authorize, HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
        public ActionResult SendMail(FormCollection forms)
        {
            string username = forms["txtReceiver"];
            var subject = forms["txtEmailText"];
            var body = forms["txtEmailBody"];
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body))
            {
                WebMail.Send(_context.RootWeb.Title, username, subject, body);
                return PartialView("MailSent");
            }

            ViewData["Receiver"] = username;
            return PartialView();
        }

        [Authorize, HttpPost, ValidateAntiForgeryToken, ValidateInput(false)]
        public bool SendMsg(string to, string subject, string content)
        {
            if (!string.IsNullOrEmpty(to))
            {
                var users = to.Split(';');
                foreach (var user in users)
                {
                    if (Membership.GetUser(user) != null)
                    {
                        _context.DataContext.Add(new PrivateMessage()
                        {
                            Content = content,
                            Title = subject,
                            Sender = User.Identity.Name,
                            Receivers = user,
                            UserName=user
                        });
                        
                        _context.DataContext.Add(new PrivateMessage()
                        {
                            Content = content,
                            Title = subject,
                            Sender = User.Identity.Name,
                            Receivers = user,
                            UserName = User.Identity.Name
                        });

                    }
                }
                _context.DataContext.SaveChanges();
            }
            return true;
        }

        [Authorize, Pagable]
        public ActionResult Inbox(QueryParams query)
        {
            if (_context.EnablePersonalWeb && _context.Web==null)
            {
                return RedirectToAction("SetupMysite", "Solution", new { Area = "" });
            }

            var total = 0;
            //var data = _context.DataContext.PrivateMessages.GetReceives(User.Identity.Name, out total, query.Index - 1, query.Size);
            IQueryable<PrivateMessage> data;
            var userName = User.Identity.Name;
            var skips = query.GetSkipRecordCount(true);
            var linq = _context.DataContext.Where<PrivateMessage>(p => p.UserName.Equals(userName,StringComparison.OrdinalIgnoreCase)).OrderByDescending(p => p.Sent);
            total = linq.Count();
            //var query = dbSet.Where(p => p.Receivers.Contains(userName)).OrderByDescending(p => p.Sent);
            if (skips > 0)
                data = linq.Skip(skips).Take(query.Size);
            else
                data= linq.Take(query.Size);

            //ViewBag.Title = GE.Global("RES_INBOX");
            //ViewBag.ImageUrl = Url.Content("~/content/images/icon_inbox_48.png");
            //ViewBag.Desc = GE.Global("AccountController_INBOX_DESC");// "View all your received messages.";
            return View("MessageBox", new ModelWrapper(data, total));
        }
        
        [Authorize,HttpPost]
        public void DeleteMsg(int id)
        {
            var msg = _context.DataContext.Find<PrivateMessage>(id);
            if (msg != null)
            {
                _context.DataContext.Delete(msg);
                _context.DataContext.SaveChanges();
            }
        }

        //[PersonalOnly, Pagable, MyControlPanel(Group = "Message box", GroupResKey = "RES_MSGBOX", ResKey = "RES_OUTBOX", Text = "Outbox", Sequence = 2)]
        //public ActionResult Outbox(QueryParams query)
        //{
        //    var total = 0;
        //    var data = _context.DataContext.PrivateMessages.GetSent(User.Identity.Name, out total, query.Index - 1, query.Size);
        //    ViewBag.Title = GE.Global("RES_OUTBOX");
        //    ViewBag.ImageUrl = Url.Content("~/content/images/icon_outbox_48.png");
        //    ViewBag.Desc = GE.Global("AccountController_OUTBOX_DESC");// "View all your sent messages.";
        //    return View("MessageBox", new ModelWrapper(data, total));
        //}

        public string GetGravatarUrl(string email, int size = 80)
        {
            if (!string.IsNullOrEmpty(email))
            {
                return "http://www.gravatar.com/avatar/" + UserExtensions.MD5Hash(email.ToLower()).ToLower() + (size > 0 ? "?s=" + size.ToString() : "");
            }

            return Url.Content("~/Content/Images/no-avatar.gif");
        }

        public string Gravatar(string name, int size = 80)
        {
            var user = Membership.GetUser(name);
            if (user == null)
                GetGravatarUrl("none@email.com", size);
            return GetGravatarUrl(user.Email, size);
        }

        #region For OpenID Test

        static private readonly OpenIdRelyingParty Openid = new OpenIdRelyingParty();
        static private readonly InMemoryTokenManager TokenManager = new InMemoryTokenManager("consumerKey", "consumerSecret");
        //private static InMemoryTokenManager TwitterTokenManager = new InMemoryTokenManager("Twitter Consumer key", "Twitter Consumer secret");

        private InMemoryTokenManager TwitterTokenManager
        {
            get
            {
                var tokenManager = (InMemoryTokenManager)HttpContext.Application["TwitterTokenManager"];
                if (tokenManager == null)
                {
                    string consumerKey = WebConfigurationManager.AppSettings["twitterConsumerKey"];
                    string consumerSecret = WebConfigurationManager.AppSettings["twitterConsumerSecret"];
                    if (!string.IsNullOrEmpty(consumerKey))
                    {
                        tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
                        HttpContext.Application["TwitterTokenManager"] = tokenManager;
                    }
                }

                return tokenManager;
            }
        }

        [ValidateInput(false)]
        public ActionResult OpenId(string openIdUrl)
        {
            var response = Openid.GetResponse();
            if (response == null)
            {
                // User submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openIdUrl, out id))
                {
                    try
                    {
                        var request = Openid.CreateRequest(openIdUrl);
                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        request.AddExtension(fetch);
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewData.ModelState.AddModelError("", ex.Message);
                        return View("Login");
                    }
                }
                return RedirectToAction("Login");
            }

            // OpenID Provider sending assertion response
            switch (response.Status)
            {
                case AuthenticationStatus.Authenticated:
                    var fetch = response.GetExtension<FetchResponse>();
                    string firstName = "unknown";
                    string lastName = "unknown";
                    string email = "unknown";
                    if (fetch != null)
                    {
                        firstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                        lastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                        email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                    }
                    return BindOpenIDToLocalAccount(response.ClaimedIdentifier, firstName, lastName, email);
                case AuthenticationStatus.Canceled:
                    ViewData.ModelState.AddModelError("", Resources.language.OpenID_Cancelled);
                    return View("Login");
                case AuthenticationStatus.Failed:
                    ViewData.ModelState.AddModelError("", Resources.language.OpenID_Exception);
                    return View("Login");
            }
            return RedirectToAction("Login");
        }

        [PersonalOnly]
        public void DeleteOpenID(string openID)
        {
            _context.DataContext.OpenIDs.DeleteOpenID(User.Identity.Name, openID);
            _context.DataContext.SaveChanges();
        }

        public ActionResult TwitterOAuth()
        {
            var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, TwitterTokenManager);
            var callBackUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Authority + "/Account/TwitterCallback");
            //twitter.Channel.Send(twitter.PrepareRequestUserAuthorization(callBackUrl, null, null));
            try
            {
                twitter.Channel.Send(twitter.PrepareRequestUserAuthorization());
                return RedirectToAction("Login");
            }
            catch (Exception e)
            {
                ViewData.ModelState.AddModelError("", e.Message);
                return View("Login");
            }
        }

        public ActionResult TwitterCallback()
        {
            var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, TwitterTokenManager);
            var accessTokenResponse = twitter.ProcessUserAuthorization();
            if (accessTokenResponse != null)
            {
                string userName = accessTokenResponse.ExtraData["screen_name"];
                return BindOpenIDToLocalAccount(userName, null, null, null);
            }
            return RedirectToAction("Login");
        }

        [HttpPost]
        public string FBConnect(string username, Facebook.UserProfile user)
        {
            if (user == null || string.IsNullOrEmpty(user.Email))
                return Url.Action("Login");

            var userName = Membership.GetUserNameByEmail(user.Email);

            if (!string.IsNullOrEmpty(userName))
            {
                var membershipUser = Membership.GetUser(userName);
                var profile = membershipUser.GetProfile();

                if (!string.IsNullOrEmpty(profile.Facebook) && profile.Facebook.Equals(user.Link))
                {
                    profile.Facebook = user.Link;
                }
                profile.Save();
                FormsAuth.SignIn(userName, true);
            }
            else
            {
                string pwd = Membership.GeneratePassword(6, 1);
                var newUser = Membership.CreateUser(username, pwd, user.Email);
                Roles.AddUserToRole(username, "guests");
                var registerEvent = new UserRegistedEvent(username, pwd, user.Email);
                registerEvent.Raise(HttpContext);

                var newProfile = newUser.GetProfile();
                newProfile.FirstName = user.First_Name;
                newProfile.LastName = user.Last_Name;
                //newProfile.DisplayName = user.Name;
                newProfile.Country = user.Locale;
                newProfile.Facebook = user.Link;
                newProfile.Signature = user.Bio;
                newProfile.Save();
            }

            if (!string.IsNullOrEmpty(Request.QueryString["returnUrl"]))
                return Url.Content(Server.UrlDecode(Request.QueryString["returnUrl"]));
            else
            {
                if (_context.EnablePersonalWeb)
                    return Url.Content(_context.ApplicationPath + "/sites/" + userName + "/index.html");
                return Url.Content((!string.IsNullOrEmpty(_context.Web.DefaultUrl) ? _context.Web.DefaultUrl : _context.ApplicationPath));
            }
        }

        [PersonalOnly, Authorize]
        [MyControlPanel(Text = "OpenID", Group = "Personal", GroupResKey = "RES_PERSONAL_SETTINGS")]
        public ActionResult MyOpenIDs()
        {
            return View(_context.DataContext.OpenIDs.GetUserIDs(User.Identity.Name));
        }

        [PersonalOnly, HttpPost, MyControlPanel]
        public ActionResult MyOpenIDs(string openID)
        {
            if (string.IsNullOrEmpty(openID))
                ViewBag.Error = "OpenID " + Resources.language.RES_REQUIRED;
            else
            {
                var _result = _context.DataContext.OpenIDs.AddOpenID(User.Identity.Name, openID.Trim());
                _context.DataContext.SaveChanges();
                if (!_result)
                    ViewBag.Error = Resources.language.OpenID_IsUsed;
            }

            return View(_context.DataContext.OpenIDs.GetUserIDs(User.Identity.Name));
        }

        private ActionResult BindOpenIDToLocalAccount(string userName, string firstName, string lastName, string email)
        {
            var registerUserName = string.IsNullOrEmpty(email) ? string.Empty : Membership.GetUserNameByEmail(email);
            bool binded = false;

            if (string.IsNullOrEmpty(registerUserName))
            {
                var _user = _context.DataContext.OpenIDs.Find(userName);
                if (_user != null)
                {
                    registerUserName = _user.UserName;
                    binded = true;
                }
            }

            if (!string.IsNullOrEmpty(registerUserName))
            {
                FormsAuth.SignIn(registerUserName, true);
                if (!binded)
                {
                    _context.DataContext.OpenIDs.AddOpenID(registerUserName, userName);
                    _context.DataContext.SaveChanges();
                }

                if (_context.EnablePersonalWeb)
                    return Redirect(_context.ApplicationPath + "/sites/" + registerUserName + "/index.html");
                return Redirect((!string.IsNullOrEmpty(_context.Web.DefaultUrl) ? _context.Web.DefaultUrl : _context.ApplicationPath));
            }
            else
            {
                return RedirectToAction("Register", new { openId = userName });
            }
        }

        #endregion
    }
}
